package com.egreen.system.repository.Impl;

import com.egreen.system.repository.VerificationCodeRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.Duration;

@Service
public class VerificationCodeRedisRepositoryImpl implements VerificationCodeRedisRepository {
    @Autowired(required = false)
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 判断缓存中是否存在该条记录
     */
    @Override
    public Boolean exist(Long userId) {
        String key = KEY_CODE + userId;
        return redisTemplate.hasKey(key);
    }

    /**
     * 将当前用户的验证码加进缓存
     */
    @Override
    public void save(Long userId, String code) {
        String KEY = KEY_CODE + userId;
        Duration duration = Duration.ofMinutes(MIN);
        //将当前验证码添加到缓存中，设置定时时间为MIN分钟
        redisTemplate.opsForValue().set(KEY, code, duration);
    }

    /**
     * 将当前用户的验证码删除（用于重新发送验证码）
     */
    @Override
    public void deleteCode(Long userId) {
        String KEY = KEY_CODE + userId;
        redisTemplate.delete(KEY);
    }

    /**
     * 获取验证码
     */
    @Override
    public String getKeyCode(Long userId) {
        String KEY = KEY_CODE + userId;
        //从缓存中拿到数据
        Serializable result = redisTemplate.opsForValue().get(KEY);
        if (result == null) {
            return null;
        }
        return String.valueOf(result);
    }

    /*String*/

    /**
     * 判断缓存中是否存在该条记录
     */
    @Override
    public Boolean exist(String userKey) {
        String key = KEY_CODE + userKey;
        return redisTemplate.hasKey(key);
    }

    /**
     * 将当前用户的验证码加进缓存
     */
    @Override
    public void save(String userKey, String code) {
        String KEY = KEY_CODE + userKey;
        Duration duration = Duration.ofMinutes(MIN);
        //将当前验证码添加到缓存中，设置定时时间为MIN分钟
        redisTemplate.opsForValue().set(KEY, code, duration);
    }

    /**
     * 将当前用户的验证码删除（用于重新发送验证码）
     */
    @Override
    public void deleteCode(String userKey) {
        String KEY = KEY_CODE + userKey;
        redisTemplate.delete(KEY);
    }

    /**
     * 获取验证码
     */
    @Override
    public String getKeyCode(String userKey) {
        String KEY = KEY_CODE + userKey;
        //从缓存中拿到数据
        Serializable result = redisTemplate.opsForValue().get(KEY);
        if (result == null) {
            return null;
        }
        return String.valueOf(result);
    }
}
